/**
 * @class Cook
 * @method init 初始化状态
 * @method work 被雇佣
 * @method rest 被解雇
 * @method toCooking 开始做饭
 * @method createProcess 创建工作进度
 * @method refreshProcess 刷新工作状态
 * @method throwFood 提交食物
 * @method cookFinish 做完处理
 * @method tryNewDish 尝试抓取新任务
 *
 */

class Cook {
  constructor(id, ele) {
    this.id = id;
    this.ele = ele;
    this.tags = this.ele.querySelector('.tags');
    this.colorStyle = null;
    this.init();
  }

  init() {
    this.onServe = false;
    this.cooking = null;
    this.workTime = 0;
    this.timer = null;
    this.serveFor = null;
    this.colorStyle = null;
  }

  work() {
    this.init();
    this.colorStyle = restaurant.addProcess(this.ele);
    this.ele.classList.remove('delSit');
    this.onServe = true;
    this.tryNewDish();
  }

  rest() {
    if (this.cooking !== null) {
      return false;
    }
    this.ele.classList.add('delSit');
    this.init();
    return true;
  }

  createProcess(title) {
    this.curProcessEle = document.createElement('div');
    this.curProcessEle.classList.add('tag');
    this.curProcessEle.innerHTML = `
      <div class="process gray LR">
        <div class="haveWork"></div>
      </div>
      <div class="box-text">${title}</div>
    `;
    restaurant.addProcess(this.curProcessEle, this.colorStyle);
    this.tags.appendChild(this.curProcessEle);
  }

  refreshProcess() {
    const passed = this.timer.count;
    this.curProcessEle.querySelector('.haveWork').style.width = `${
      (passed / this.cookTime) * 100
    }%`;
  }

  throwFood() {
    const reqIndex = this.serveFor.curWaits.findIndex(
      (d) => d.food.id === this.cooking.id,
    );
    if (!this.serveFor.curWaits[reqIndex].isTimeOut) {
      this.serveFor.saveFood(reqIndex);
    }
    this.cookFinish();
  }

  cookFinish() {
    this.cooking = null;
    this.timer = null;
    this.serveFor = null;
    this.curProcessEle.remove();
    this.tryNewDish();
  }

  tryNewDish() {
    const d = restaurant.foodWaitQueue.shift();
    if (d) {
      this.toCooking(restaurant.config.foods[d.foodId], d.customer);
    }
  }

  toCooking(food, customer) {
    this.serveFor = customer;
    this.createProcess(food.foodName);
    this.cooking = food;
    this.cookTime = food.cookTime;
    this.timer = new Timer(
      100,
      this.cookTime,
      () => window.game.pause,
      () => {
        this.refreshProcess();
      },
      () => {
        this.throwFood();
      },
    );
    this.timer.start();
    restaurant.state.money -= food.cost;
    new AlertBox(
      `为做${food.foodName}支出${food.cost}元`,
      1000,
    );
  }
}
